import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: JSON.parse(localStorage.getItem('user')) || null,
    questions: [], 
    answers: [],
    currentQuestionIndex: 0,
    wrongQuestions: JSON.parse(localStorage.getItem('wrongQuestions')) || [], // 错题记录
    examMode: false, // 是否处于考试模式
    examStartTime: null, // 考试开始时间
    examTimeLimit: 30 * 60 * 1000, // 考试时间限制（30分钟）
    // 智能推荐模式相关状态
    smartRecommendMode: false, // 是否处于智能推荐模式
    currentRecommendQuestion: null, // 当前智能推荐模式的题目
    recommendSessionId: null, // 智能推荐会话ID
    recommendAnswers: [], // 智能推荐模式的答案记录
    recommendCorrectCount: 0 // 智能推荐模式正确题目数
  },
  getters: {
    currentQuestion: (s) => {
      // 智能推荐模式下返回当前题目
      if (s.smartRecommendMode && s.currentRecommendQuestion) {
        return s.currentRecommendQuestion;
      }
      // 详细模式下返回题目列表中的当前题目
      return s.questions && s.questions.length > 0 ? s.questions[s.currentQuestionIndex] : null;
    },
    isFinished: (s) => {
      // 智能推荐模式下，当没有下一题时结束
      if (s.smartRecommendMode) {
        return !s.currentRecommendQuestion;
      }
      // 详细模式下，当完成所有题目时结束
      return !s.questions || s.questions.length === 0 || s.currentQuestionIndex >= s.questions.length;
    },
    summary: (s) => {
      if (s.smartRecommendMode) {
        // 智能推荐模式下的答题总结
        return s.recommendAnswers.map(a => ({
          id: a.questionId,
          question: a.question,
          userAnswer: a.answer,
          correct: a.correct,
          explanation: a.explanation
        }));
      }
      
      // 详细模式下的答题总结
      if (!s.questions || s.questions.length === 0) return [];
      return s.answers.map((a,i) => {
        const q = s.questions[i];
        if (!q) return null;
        return {
          id: q.id,
          question: q.question,
          userAnswer: a.answer,
          correct: a.correct,
          explanation: q.explanation
        };
      }).filter(item => item !== null);
    },
    score: (s) => {
      if (s.smartRecommendMode) {
        return s.recommendCorrectCount;
      }
      return s.answers.filter(x => x.correct).length;
    },
    total: (s) => {
      if (s.smartRecommendMode) {
        return s.recommendAnswers.length;
      }
      return s.questions ? s.questions.length : 0;
    },
    wrongQuestionsList: (s) => s.wrongQuestions,
    examTimeRemaining: (s) => {
      if (!s.examMode || !s.examStartTime) return null;
      const elapsed = Date.now() - s.examStartTime;
      const remaining = s.examTimeLimit - elapsed;
      return Math.max(0, remaining);
    },
    isExamTimeUp: (s, g) => {
      return s.examMode && g.examTimeRemaining <= 0;
    }
  },
  mutations: {
    nextQuestion(state,answer){
      // 检查是否有题目数据
      if (!state.questions || state.questions.length === 0) {
        console.warn('没有可用的题目数据');
        return;
      }
      
      state.answers.push(answer)
      state.currentQuestionIndex++
      
      // 如果答错了，记录到错题本
      if (!answer.correct) {
        const question = state.questions[state.currentQuestionIndex - 1];
        if (question) {
          const wrongQuestion = {
            ...question,
            userAnswer: answer.answer,
            wrongTime: Date.now()
          };
          
          // 避免重复添加
          const exists = state.wrongQuestions.find(q => q.id === question.id);
          if (!exists) {
            state.wrongQuestions.push(wrongQuestion);
            localStorage.setItem('wrongQuestions', JSON.stringify(state.wrongQuestions));
          }
        }
      }
    },
    
    // 智能推荐模式相关mutations
    setSmartRecommendMode(state, { enabled, sessionId }) {
      state.smartRecommendMode = enabled;
      state.recommendSessionId = sessionId;
      if (enabled) {
        // 进入智能推荐模式时重置相关状态
        state.recommendAnswers = [];
        state.recommendCorrectCount = 0;
        state.currentRecommendQuestion = null;
      }
    },
    
    setCurrentRecommendQuestion(state, question) {
      state.currentRecommendQuestion = question;
    },
    
    addRecommendAnswer(state, answerData) {
      state.recommendAnswers.push(answerData);
      if (answerData.correct) {
        state.recommendCorrectCount++;
      }
    },
    
    reset(state){
      state.currentQuestionIndex = 0
      state.answers = []
      state.examMode = false
      state.examStartTime = null
      // 重置智能推荐模式状态
      state.smartRecommendMode = false
      state.recommendSessionId = null
      state.currentRecommendQuestion = null
      state.recommendAnswers = []
      state.recommendCorrectCount = 0
    },
    
    setUser(state, user) {
      state.user = user
    },
    
    initializeQuestions(state, { studyModeId, questionTypeId }) { 
      // 检查是否有题目数据
      if (!state.questions || state.questions.length === 0) {
        console.warn('没有可用的题目数据，请先通过API获取题目');
        return;
      }
      
      // 根据题型筛选题目
      let filteredQuestions = [];
      if (questionTypeId && questionTypeId !== 'all') {
        // 根据题型筛选题目
        filteredQuestions = state.questions.filter(q => q.questionTypeId === questionTypeId);
      } else {
        // 如果没有指定类型，则使用所有题目
        filteredQuestions = state.questions;
      }
      
      // 根据模式处理题目
      if (studyModeId === 'review') {
        // 错题复习模式：从错题记录中获取题目
        if (state.wrongQuestions.length > 0) {
          filteredQuestions = state.wrongQuestions.map(wq => ({
            id: wq.id,
            type: wq.type,
            concept: wq.concept,
            question: wq.question,
            options: wq.options,
            answer: wq.answer,
            explanation: wq.explanation
          }));
        } else {
          // 如果没有错题记录，使用所有题目
          filteredQuestions = filteredQuestions.slice(0, 10);
        }
      } else if (studyModeId === 'exam') {
        // 考试模式：随机打乱题目顺序，设置考试模式
        filteredQuestions = [...filteredQuestions].sort(() => Math.random() - 0.5);
        state.examMode = true;
        state.examStartTime = Date.now();
      }
      
      // 更新state
      state.questions = filteredQuestions;
      state.currentQuestionIndex = 0;
      state.answers = [];
    },
    
    clearWrongQuestions(state) {
      state.wrongQuestions = [];
      localStorage.removeItem('wrongQuestions');
    },
    
    setQuestions(state, questions) {
      state.questions = questions;
    }
  },
  actions: {
    logout({ commit }) {
      // 清除用户信息与运行时学习状态
      commit('setUser', null)
      commit('reset')

      // 清除本地存储（JWT与用户、记住我、错题记录等）
      try {
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        localStorage.removeItem('rememberMe')
        localStorage.removeItem('wrongQuestions')
      } catch (e) {
        // 忽略本地存储清理异常，确保登出流程不中断
        console.warn('清理本地存储时出错: ', e)
      }
    }
  },
  modules: {
  }
})
